package com.xbongbong.crm.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.util.HttpDeleteWithBody;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.SearchCustomerTemplateModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.common.pojo.AddressPojo;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.domain.entity.SearchCustomerTemplateEntity;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.searchcustomer.pojo.SearchCustomerFieldPojo;
import com.xbongbong.pro.searchcustomer.pojo.dto.Clue;
import com.xbongbong.pro.searchcustomer.pojo.dto.ClueContact;
import com.xbongbong.pro.searchcustomer.pojo.dto.SearchCustomerDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author shian
 * @create 2019-08-01 13:35
 * @Description
 */
@Component
public class SearchCustomerHelp {

    @Resource
    public PaasRedisHelper paasRedisHelper;
    @Resource
    public PaasFormExplainModel paasFormExplainModel;
    @Resource
    private SearchCustomerTemplateModel searchCustomerTemplateModel;
    @Resource
    private RestTemplate restTemplate;

    private static final Logger LOG = LoggerFactory.getLogger(SearchCustomerHelp.class);

    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    /**
     * 栗子AK与AS
     */
    private static final String API_KEY = ProBaseConfig.getClueAk();
    private static final String API_SECRET = ProBaseConfig.getClueAs();

    /**
     * 工商AK与AS
     */
    private static final String API_KEY_2 = "219a20085e5e44d997dd1930ee656c23";
    private static final String API_SECRET_2 = "52e5483d42c34b4da6e7eea53e38e533";

    /**
     * 搜客已经处理过的值，不对默认值做处理
      */
    private static final List searchCustomerAttrList = Arrays.asList(CustomerManagementEnum.NAME.getAttr(),CustomerManagementEnum.NAME_SHORT.getAttr(),CustomerManagementEnum.ADDRESS.getAttr(),CustomerManagementEnum.ADD_CONTACT.getAttr(),CustomerManagementEnum.PHONE.getAttr(),CustomerManagementEnum.IS_PUBLIC.getAttr(),
            CustomerManagementEnum.OWNER_ID.getAttr(),CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(),CustomerManagementEnum.IS_ARCHIVED.getAttr(),CustomerManagementEnum.CREATOR.getAttr(), CustomerManagementEnum.CUSTOMER_STAGE.getAttr(),CustomerManagementEnum.CLUE_COMPANY_ID.getAttr(),CustomerManagementEnum.SCORE.getAttr());

    /**
     * 使用SHA1加密
     * @param
     * @return com.alibaba.fastjson.JSONObject
     * @author 石安
     * @date 2019-08-02
     */
    private static JSONObject encrypt(String secret){
        String timestamp = String.valueOf(System.currentTimeMillis());
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac;
        String sign = "";
        try {
            mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
            sign = Base64.getEncoder().encodeToString(mac.doFinal(timestamp.getBytes()));
        } catch (Exception e) {
            LOG.error("使用SHA1加密报错：" + e.getMessage());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("sign", sign);
        return jsonObject;
    }

    public JSONObject httpExchange(String url, Object data, HttpMethod httpMethod, SoukeMealEnum soukeMealEnum) throws XbbException{
        String secret = "";
        String key = "";
        if (Objects.equals(soukeMealEnum, SoukeMealEnum.SOUKE)) {
            secret = API_SECRET;
            key = API_KEY;
        } else if (Objects.equals(soukeMealEnum, SoukeMealEnum.BUSINESS)){
            secret = API_SECRET_2;
            key = API_KEY_2;
        }
        // 获取加密信息
        JSONObject info = encrypt(secret);
        String timestamp = info.getString("timestamp");
        String sign = info.getString("sign");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set("X-AK-KEY", key);
        httpHeaders.set("X-AK-TS", timestamp);
        httpHeaders.set("X-AK-PIN", sign);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(data), httpHeaders);

        ResponseEntity<String> exchange;
        try {
            exchange = restTemplate.exchange(url, httpMethod, requestEntity, String.class);
        } catch (RestClientException e) {
            LOG.error("搜客请求报错", e);
            exchange = null;
        }
        if (Objects.isNull(exchange)) {
            return null;
        }
        String body = exchange.getBody();
        LOG.info("请求结果result =" + body);

        return JSON.parseObject(body);
    }

    /**
     * 通过不同的请求方式发送到搜客接口（调用栗子接口）
     * @param url
     * @param data
     * @param method
     * @return com.alibaba.fastjson.JSONObject
     * @author 石安
     * @date 2019-08-05
     */
    @Deprecated
    public JSONObject http(String url, Object data, String method) throws XbbException{
        // 获取加密信息
        JSONObject info = encrypt(API_SECRET);
        String timestamp = info.getString("timestamp");
        String sign = info.getString("sign");

        HttpRequestBase httpRequestBase = null;
        CloseableHttpResponse response = null;

        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(5000).build();
        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
        switch (method){
            case "GET":
                httpRequestBase = new HttpGet(url);
                break;
            case "POST":
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(requestEntity);
                httpRequestBase = httpPost;
                break;
            case "PATCH":
                HttpPatch httpPatch = new HttpPatch(url);
                httpPatch.setEntity(requestEntity);
                httpRequestBase = httpPatch;
                break;
            case "PUT":
                HttpPut httpPut = new HttpPut(url);
                httpPut.setEntity(requestEntity);
                httpRequestBase = httpPut;
                break;
            case "DELETE":
                HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
                httpDelete.setEntity(requestEntity);
                httpRequestBase = httpDelete;
                break;
            default:
                break;
        }
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            if (httpRequestBase != null){
                httpRequestBase.setConfig(requestConfig);
                httpRequestBase.addHeader("Content-Type", "application/json");
                httpRequestBase.addHeader("X-AK-KEY", API_KEY);
                httpRequestBase.addHeader("X-AK-TS", timestamp);
                httpRequestBase.addHeader("X-AK-PIN", sign);

                response = httpClient.execute(httpRequestBase, new BasicHttpContext());
                if (response.getStatusLine().getStatusCode() != 200) {

                    LOG.error("request url failed, http code=" + response.getStatusLine().getStatusCode()
                            + ", url=" + url);
                    return null;
                }
                org.apache.http.HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String resultStr = EntityUtils.toString(entity, "utf-8");
                    LOG.info("resultStr = "+ resultStr);
                    return JSON.parseObject(resultStr);
                }
            }

        } catch (IOException e) {
            LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 调用工商接口
     * @param url
     * @param data
     * @param method
     * @return com.alibaba.fastjson.JSONObject
     * @author 石安
     * @date 2019-08-15
     */
    @Deprecated
    public JSONObject httpBusiness(String url, Object data, String method) throws XbbException {
        String timestamp = String.valueOf(System.currentTimeMillis());
        SecretKeySpec signingKey = new SecretKeySpec(API_SECRET_2.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac;
        String sign = "";
        try {
            mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
            sign = Base64.getEncoder().encodeToString(mac.doFinal(timestamp.getBytes()));
        } catch (Exception e) {
            LOG.error("使用SHA1加密报错(工商查询)：" + e.getMessage());
        }
        HttpRequestBase httpRequestBase = null;
        CloseableHttpResponse response = null;

        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(5000).build();
        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
        switch (method){
            case "GET":
                httpRequestBase = new HttpGet(url);
                break;
            case "POST":
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(requestEntity);
                httpRequestBase = httpPost;
                break;
            case "PATCH":
                HttpPatch httpPatch = new HttpPatch(url);
                httpPatch.setEntity(requestEntity);
                httpRequestBase = httpPatch;
                break;
            case "PUT":
                HttpPut httpPut = new HttpPut(url);
                httpPut.setEntity(requestEntity);
                httpRequestBase = httpPut;
                break;
            case "DELETE":
                httpRequestBase = new HttpDelete(url);
                break;
            default:
                break;
        }

        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            if (httpRequestBase != null) {
                httpRequestBase.setConfig(requestConfig);
                httpRequestBase.addHeader("Content-Type", "application/json");
                httpRequestBase.addHeader("X-AK-KEY", API_KEY_2);
                httpRequestBase.addHeader("X-AK-TS", timestamp);
                httpRequestBase.addHeader("X-AK-PIN", sign);
                response = httpClient.execute(httpRequestBase, new BasicHttpContext());

                if (response.getStatusLine().getStatusCode() != 200) {

                    LOG.error("request url failed, http code=" + response.getStatusLine().getStatusCode()
                            + ", url=" + url);
                    return null;
                }
                org.apache.http.HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String resultStr = EntityUtils.toString(entity, "utf-8");
                    LOG.info("resultStr = " + resultStr);
                    return JSON.parseObject(resultStr);
                }
            }
        } catch (IOException e) {
            LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 获取搜客的默认模板
     * @author 石安
     * @date 2019-08-09
     */
    public SearchCustomerTemplateEntity getInitTemplate() throws XbbException{

        Map<String, Object> param = new HashMap<>(16);
        param.put("formId", 0);
        param.put("corpid", 0);
        param.put("del", DelEnum.NORMAL.getDel());

        List<SearchCustomerTemplateEntity> list = searchCustomerTemplateModel.findEntitys(param);

        return list.get(0);
    }

    /**
     * 过滤掉不需要的字段类型
     * @param explainList
     * @author 石安
     * @date 2019-08-09
     */
    public List<SearchCustomerFieldPojo> setFieldAttrAllow(List<FieldAttrEntity> explainList) {
        List<SearchCustomerFieldPojo> objectList = new ArrayList<>();
        // 产品要求：只展示单行文本，单选按钮，下拉框，数字，日期，复选按钮，下拉复选
        explainList.forEach(item->{
            SearchCustomerFieldPojo pojo = new SearchCustomerFieldPojo();
            if(Objects.equals(item.getFieldType(),FieldTypeEnum.TEXT.getType()) || Objects.equals(item.getFieldType(),FieldTypeEnum.NUM.getType())
                    || Objects.equals(item.getFieldType(),FieldTypeEnum.COMBO.getType()) || Objects.equals(item.getFieldType(),FieldTypeEnum.DATETIME.getType())
                    || Objects.equals(item.getFieldType(),FieldTypeEnum.RADIO_GROUP.getType()) || Objects.equals(item.getFieldType(),FieldTypeEnum.COMBO_CHECK.getType())
                    || Objects.equals(item.getFieldType(),FieldTypeEnum.CHECKBOX_GROUP.getType())){
                BeanUtil.copyProperties(item, pojo);
                objectList.add(pojo);
            }
        });

        return  objectList;
    }

    /**
     * 将搜客的客户数据按模糊匹配模板转客户数据
     * @param clue
     * @param searchCustomerDataDTO
     * @return com.alibaba.fastjson.JSONObject
     * @author 石安
     * @date 2019-08-14
     */
    public JSONObject changeData(Clue clue, SearchCustomerDataDTO searchCustomerDataDTO){
        Long formId = searchCustomerDataDTO.getFormId();
        String corpid = searchCustomerDataDTO.getCorpid();

        JSONObject jsonObject = new JSONObject();
        String entname = clue.getEntname();
        String address = clue.getAddress();
        // 企业移动电话
        String telephoneMobile = clue.getTelephoneMobile();
        // 企业固定电话
        String telephoneFixed = clue.getTelepohneFixed();
        JSONArray phoneArray = new JSONArray();
        if (!StringUtil.isEmpty(telephoneMobile)){
            JSONObject phone = new JSONObject();
            // 电话类型写死为工作（搜客的电话类型与我们的不一致）
            phone.put("text_1","1");
            phone.put("text_2", telephoneMobile);
            phoneArray.add(phone);
        }
        if (!StringUtil.isEmpty(telephoneFixed)){
            JSONObject phone = new JSONObject();
            phone.put("text_1","1");
            phone.put("text_2", telephoneFixed);
            phoneArray.add(phone);
        }

        if (phoneArray.size() == 0){
            JSONObject phone = new JSONObject();
            phone.put("text_1","1");
            phone.put("text_2", StringConstant.SOUKE_TELE_VALUE);
            phoneArray.add(phone);
        }
        JSONObject addr = changeAddress(address);
        if (addr == null) {
            addr = new JSONObject();
            addr.put("address", address);
            addr.put("province", "");
            addr.put("city", "");
            addr.put("district", "");
        }

        List<ClueContact> contacts = clue.getContacts();

        JSONArray contactArray = new JSONArray();
        // 将搜客的联系人转成客户的联系人数据格式
        if (contacts.size() > 0){
            for (ClueContact item : contacts) {
                JSONObject contactObj = new JSONObject();
                contactObj.put("dataId", null);

                JSONObject data = new JSONObject();
                JSONArray contactPhoneArray = new JSONArray();
                JSONObject contactPhoneObj = new JSONObject();
                if (!StringUtil.isEmpty(item.getValue())) {
                    // 电话类型写死为工作（搜客的电话类型与我们的不一致）
                    contactPhoneObj.put("text_1","1");
                    contactPhoneObj.put("text_2", item.getValue());
                    contactPhoneArray.add(contactPhoneObj);
                    data.put(ContactEnum.PHONE.getAttr(), contactPhoneArray);
                }
                if (item.getData().size() > 0) {
                    // 只取搜客那边的多个来源站的第一个联系人名称（产品说的）
                    if (!StringUtil.isEmpty(item.getData().get(0).getContact())) {
                        data.put(ContactEnum.NAME.getAttr(), item.getData().get(0).getContact());
                    }
                    // 只取搜客那边的多个来源站的第一个地址（产品说的）
                    JSONObject contactAddress = changeAddress(item.getData().get(0).getAddress());
                    if (Objects.isNull(contactAddress)) {
                        contactAddress = new JSONObject();
                        contactAddress.put("address", item.getData().get(0).getAddress());
                        contactAddress.put("province", "");
                        contactAddress.put("city", "");
                        contactAddress.put("district", "");
                    }
                    data.put(ContactEnum.ADDRESS.getAttr(), contactAddress);
                }
                data.put(ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), entname);
                // 联系人负责人
                data.put(ContactEnum.OWNER_ID.getAttr(), searchCustomerDataDTO.getOwnerId());
                contactObj.put("data", data);
                contactObj.put(StringConstant.OPERATION_FLAG, BasicConstant.ZERO);
                contactObj.put("serialNo", "");
                contactArray.add(contactObj);
             }
        }
        jsonObject.put(CustomerManagementEnum.NAME.getAttr(), entname);
        jsonObject.put(CustomerManagementEnum.PHONE.getAttr(), phoneArray);
        if (!StringUtil.isEmpty(clue.getContact())){
            jsonObject.put(CustomerManagementEnum.NAME_SHORT.getAttr(), clue.getContact());
        }
        jsonObject.put(CustomerManagementEnum.ADDRESS.getAttr(), addr);
        jsonObject.put(CustomerManagementEnum.ADD_CONTACT.getAttr(), contactArray);
        // 默认初始化
        jsonObject.put(CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(), 0);
        if (Objects.equals("转客户公海池", searchCustomerDataDTO.getTarget())) {
            jsonObject.put(CustomerManagementEnum.IS_PUBLIC.getAttr(), 1);
        } else {
            jsonObject.put(CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
        }
        jsonObject.put(CustomerManagementEnum.OWNER_ID.getAttr(), searchCustomerDataDTO.getOwnerId());
        jsonObject.put(CustomerManagementEnum.IS_ARCHIVED.getAttr(), 2);
        jsonObject.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0);
        jsonObject.put(CustomerManagementEnum.CREATOR.getAttr(), searchCustomerDataDTO.getUserId());
        jsonObject.put(CustomerManagementEnum.CLUE_COMPANY_ID.getAttr(), clue.getPid());
        //处理 bug 34450,这边只对下拉框的做了处理，没对有范围的做。改动范围太大了
        try {
            //查询客户表单解释
            PaasFormExplainEntity formExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            addDefaultValue(jsonObject, formExplainEntity);
        }catch (Exception e){
            LOG.info("字段必填默认值填充失败！");
        }
        return jsonObject;
    }

    /**
     * @Author mingliang
     * @Description 兼容省市
     * @Date 2021/11/12 17:48
     * @param addr
     **/
    public void setDefaultProvinceAndCity(JSONObject addr) {
        //市有问题兼容
        String city = addr.getString("city");
        if (Objects.equals("北京市", city)) {
            addr.put("city", "北京城区");
        } else if (Objects.equals("上海市", city)) {
            addr.put("city", "上海城区");
        } else if (Objects.equals("天津市", city)) {
            addr.put("city", "天津城区");
        } else if (Objects.equals("重庆市", city)) {
            addr.put("city", "重庆城区");
        }
        //省有问题兼容
        String province = addr.getString("province");
        if (Objects.equals("广西壮族自治区", province)) {
            addr.put("province", "广西");
        } else if (Objects.equals("西藏自治区", province)) {
            addr.put("province", "西藏");
        } else if (Objects.equals("宁夏回族自治区", province)) {
            addr.put("province", "宁夏");
        }else if (Objects.equals("新疆维吾尔自治区", province)) {
            addr.put("province", "新疆");
        } else if (Objects.equals("内蒙古自治区", province)) {
            addr.put("province", "内蒙古");
        }
    }


    /**
     * 地址转换成规范格式
     * @param oploc
     * @return com.alibaba.fastjson.JSONObject
     * @author 石安
     * @date 2019-08-19
     */
    public JSONObject changeAddress(String oploc){

        if (StringUtil.isEmpty(oploc)) {
            return null;
        }
        JSONObject addr;
        try {
            addr = GaodeGeoHelper.geo(oploc, "");

            if (addr == null) {
                addr = new JSONObject();
                addr.put("address", oploc);
                addr.put("province", "");
                addr.put("city", "");
                addr.put("district", "");
                return addr;
            }

            // 下面的操作主要是找到详细地址，暂时复杂处理，后期有时间优化
            if (!oploc.contains(I18nMessageUtil.getMessage(CommonConstant.AREA))) {
               if (!oploc.contains(I18nMessageUtil.getMessage(CommonConstant.CITY))) {
                   if (!oploc.contains(I18nMessageUtil.getMessage(CommonConstant.PROVINCE))) {
                       addr.put("address", oploc);
                   } else if (oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.PROVINCE)) > 0){
                       addr.put("address", oploc.substring(oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.PROVINCE)) + 1));
                   }
               } else if(oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.CITY)) > 0){
                   addr.put("address", oploc.substring(oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.CITY)) + 1));
               }
            } else if(oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.AREA)) > 0){
                addr.put("address", oploc.substring(oploc.indexOf(I18nMessageUtil.getMessage(CommonConstant.AREA)) + 1));
            }
            // 获取经纬度
            Double latitude = (Double) addr.get("latitude");
            Double longitude = (Double) addr.get("longitude");
            AddressPojo pojo = new AddressPojo();
            AddressPojo.Location location = pojo.new Location();
            location.setLat(latitude);
            location.setLon(longitude);
            addr.put("location", location);
            addr.remove("latitude");
            addr.remove("longitude");
        } catch (Exception e) {
            LOG.warn("(高德地图查地址出错)gaode map search error" + e.getMessage());
            return null;
        }
        setDefaultProvinceAndCity(addr);
        return addr;
    }



    /**
     * @Author mingliang
     * @Description 设置默认值
     * @Date 2021/11/8 16:29
     * @param addObject
     * @param explainEntity
     **/
    public void addDefaultValue(JSONObject addObject, PaasFormExplainEntity explainEntity) {
        String explains = explainEntity.getExplains();
        JSONArray jsonArrayExplain = JSONArray.parseArray(explains);
        for (int j = 0; j < jsonArrayExplain.size(); j++) {
            JSONObject jsonObjectExplain = jsonArrayExplain.getJSONObject(j);
            Integer fieldType = jsonObjectExplain.getInteger(FieldAttrConstant.FIELD_TYPE);
            String attr = jsonObjectExplain.getString("attr");
            JSONArray itemList = jsonObjectExplain.getJSONArray("items");
            if (Objects.equals(CustomerManagementEnum.NAME.getAttr(), attr)
                    || Objects.equals(CustomerManagementEnum.PHONE.getAttr(), attr)
                    || Objects.equals(CustomerManagementEnum.ADDRESS.getAttr(), attr)) {
                continue;
            }
            if (Objects.equals(fieldType, FieldTypeEnum.TEXT.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.TEXTAREA.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.NUM.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    Object object = defaultAttr.getObject("defaultValue", Object.class);
                    addObject.put(attr, object);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    Long object = defaultAttr.getLong("defaultValue");
                    addObject.put(attr, object);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())) {
                if (Objects.nonNull(itemList)) {
                    for (int n = 0; n < itemList.size(); n++) {
                        JSONObject item = itemList.getJSONObject(n);
                        Boolean checked = item.getBoolean("checked");
                        if (checked != null && checked) {
                            JSONObject object = new JSONObject();
                            object.put("text", item.getString("text"));
                            object.put("value", item.getString("value"));
                            addObject.put(attr, object);
                            continue;
                        }
                    }
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType()) || Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())) {
                JSONArray checkboxGroupArray = new JSONArray();
                if (Objects.nonNull(itemList)) {
                    for (int n = 0; n < itemList.size(); n++) {
                        JSONObject item = itemList.getJSONObject(n);
                        Boolean checked = item.getBoolean("checked");
                        if (checked != null && checked) {
                            checkboxGroupArray.add(item);
                        }
                    }
                }
                addObject.put(attr, checkboxGroupArray);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())) {
                JSONObject defaultAttr = jsonObjectExplain.getJSONObject("defaultAttr");
                if (Objects.nonNull(defaultAttr)) {
                    JSONArray defaultJSONArray = defaultAttr.getJSONArray("defaultValue");
                    addObject.put(attr, defaultJSONArray);
                }
            }
        }
    }
}
